package com.jinxin.platform.cdqzsqacs.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.annotation.RecEvent;
import com.jinxin.platform.base.common.pojo.InvokeCfg;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.base.common.support.BusinessDelegate;
import com.jinxin.platform.base.common.support.PlatFormEventListener;
import com.jinxin.platform.cdqzsqacs.bean.*;
import com.jinxin.platform.cdqzsqacs.common.Constant;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsDeviceMapper;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsOpenRecordMapper;
import com.jinxin.platform.cdqzsqacs.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-02-05
 * @Author: Lingnan
 **/
@Component
@RecEvent(eventType = "reportDistinguish")
@Slf4j
public class DeviceReportListener implements PlatFormEventListener {
    @Autowired
    private BusinessDelegate businessDelegate;
    @Autowired
    private CdqzsqacsDeviceMapper deviceMapper;
    @Autowired
    private CdqzsqacsOpenRecordMapper openRecordMapper;
//    @Autowired
//    private CdzxkacsUserMapper userMapper;

    @Override
    public JsonResult event(Map resultMap) {
        //{"data":{"reportMessage":"{\"r2\":\"00\",\"r3\":\"01\",\"r4\":\"00 98 \",\"r1\":\"02\"}",
        // "product_code":"00000a05","serial_num":"00000a0518110227","account":"1563700000001964",
        // "cmd_id":"4190","cmd_name":"Report"},"modules":["apcos-cqxfydjc"]}
        String upDataStr = JSON.toJSONString(resultMap);
        if(resultMap == null){return JsonResult.ok(DeviceReportListener.class);}
        if(!resultMap.containsKey("data") || !resultMap.containsKey("modules")){
            return JsonResult.ok(DeviceReportListener.class);
        }
        JSONObject upDataJson = JSONObject.parseObject(upDataStr);
        String modules = upDataJson.get("modules").toString();
        // 只处理自己模块的上报信息
        if(modules.contains(Constant.MODULE_KEY)){
            log.info("智慧社区(泉州)门禁上报: " + upDataStr);
            // 小区与设备的对应关系 <设备序列号,设备信息>
            Map<String,CdqzsqacsDevice> serIdNameMap = new HashMap<>();
            List<CdqzsqacsDevice> deviceList = deviceMapper.list(new HashMap());
            List<String> productCodeList = new ArrayList<>();//保存产品编号列表
            for(CdqzsqacsDevice device : deviceList){
                String productCode = device.getProductCode();
                if(!productCodeList.contains(productCode)){
                    productCodeList.add(productCode);
                }
                serIdNameMap.put(device.getSerialNum(),device);
            }
            JSONObject dataJson = upDataJson.getJSONObject("data");
            JSONObject reportMessage = dataJson.getJSONObject("reportMessage");
            JSONObject jsonObject = reportMessage.getJSONObject("r1");
            String serialNum = dataJson.getString("serial_num");
            if(jsonObject != null){
                CdqzsqacsOpenRecord openRecord = new CdqzsqacsOpenRecord();
                openRecord.setSerialNum(serialNum);
                CdqzsqacsDevice device = serIdNameMap.get(serialNum);
                if(device != null){
                    openRecord.setCommunityId(device.getCommunityId());
                    openRecord.setCommunityName(device.getCommunityName());
                    openRecord.setDeviceName(device.getDeviceName());
                }
                // deviceCode+timestamp 暂时作为id
                Long timestamp = jsonObject.getLong("Timestamp");//注意单位是秒 *1000 --->毫秒
                if(timestamp != null){
                    openRecord.setOpenTime(DateUtil.getDateTimeOfTimestamp(timestamp*1000));
                }
                int faceInfoNum = jsonObject.getInteger("FaceInfoNum");
                if(faceInfoNum > 0){
                    JSONArray faceInfoList = jsonObject.getJSONArray("FaceInfoList");
                    JSONObject json2 = faceInfoList.getJSONObject(0);//取第一个
                    int capSrc = json2.getInteger("CapSrc");
                    String openType;
                    switch (capSrc){
                        case 1: openType = "人脸识别";break;
                        case 2: openType = "门禁卡采集";break;
                        case 3: openType = "身份证采集";break;
                        case 4: openType = "闸机采集";break;
                        default: openType= "未知";break;
                    }
                    openRecord.setOpenType(openType);
                    JSONObject faceJson = json2.getJSONObject("FaceImage");
//                    String faceData = faceJson.getString("Data");
//                    if(!StringUtils.isEmpty(faceData)){
//                        openRecord.setCapturePic(Constant.IMG_BASE64_PREFIX+faceData);
//                    }
                }
                int cardInfoNum = jsonObject.getInteger("CardInfoNum");
                if(cardInfoNum > 0){
                    JSONArray cardInfoList = jsonObject.getJSONArray("CardInfoList");
                    JSONObject cardJson = cardInfoList.getJSONObject(0);
                    openRecord.setOpenUser(cardJson.getString("Name"));
                }
                // 库比对信息数目 范围：[0, 16]
                int libMatInfoNum = jsonObject.getInteger("LibMatInfoNum");
                if(libMatInfoNum > 0){
                    JSONArray libMatInfoList = jsonObject.getJSONArray("LibMatInfoList");
                    JSONObject libMatInfoJson = libMatInfoList.getJSONObject(0);
                    JSONObject personInfo = libMatInfoJson.getJSONObject("MatchPersonInfo");
                    String userId = libMatInfoJson.getInteger("MatchPersonID")+"";
                    String personName = personInfo.getString("PersonName");
                    if(!StringUtils.isEmpty(personName)){
                        openRecord.setOpenUser(personName);
                    }
                    if(!StringUtils.isEmpty(userId)){
                        openRecord.setOpenUserId(userId);
//                        CdzxkacsUser cdzxkacsUser = userMapper.selectByKey(userId);
                        log.info("通过识别用户id（"+userId+"）查询用户信息");
                        openRecord.setPersonType("");
                        openRecord.setPhone("");
                        if(StringUtils.isEmpty(openRecord.getOpenUser())){
                            openRecord.setOpenUser("");
                        }
                    }
                }

                String id = serialNum+timestamp;
                if(!StringUtils.isEmpty(id)){
                    openRecord.setId(id);
                    CdqzsqacsOpenRecord record = openRecordMapper.selectByKey(id);
                    if(record == null){
                        openRecordMapper.insert(openRecord);
                    }
                }
            }
        }
        return JsonResult.error(upDataStr);
    }
    /**
     * 解析服务解析主动上报返回解析结果
     * @param productCode 应用产品编号 00073601
     * @param reportMessage 请求解析参数
     * @return
     */
    private JsonResult parseReportDistinguish(String productCode, String reportMessage){
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("parseReportDistinguish");
        Map<String, String> argsMap = new HashMap<>();
        argsMap.put("productCode",productCode);
        argsMap.put("appCode",Constant.APP_CODE);
        argsMap.put("appVersion",Constant.APP_VERSION);
        argsMap.put("cmd_name", "ReportDistinguish");
        argsMap.put("reportMessage",reportMessage);
        cfg.setArgs(argsMap);
        JsonResult result = businessDelegate.invoke(cfg);
        if (result !=null && result.getSuccess()) {
            return result;
        }
        return null;
    }
}
